﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Cryptography;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using System.Text.RegularExpressions;

namespace test0320
{
    public partial class Page2: UserControl
    {
        public Page2()
        {
            InitializeComponent();
            InitializeControls();

        }
        private void InitializeControls()
        {
            // 初始化算法选择
            cmbAlgorithm.Items.AddRange(new string[] { "AES-128", "AES-192", "AES-256" });
            cmbAlgorithm.SelectedIndex = 0;

            // 设置字体
            txtciphertext.Font = new System.Drawing.Font("Consolas", 9F);
            txtKey.Font = new System.Drawing.Font("Consolas", 9F);
            txtResult.Font = new System.Drawing.Font("Consolas", 9F);

        }


        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void Page2_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            txtciphertext.Clear();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {
            txtKey.Clear();
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                // 获取输入参数
                int keySize = GetSelectedKeySize();
                string ciphertext = SanitizeHex(txtciphertext.Text);
                string key = SanitizeHex(txtKey.Text);

                // 验证输入
                ValidateInput(ciphertext, key, keySize);

                // 转换输入
                byte[] input = HexToBytes(ciphertext);
                byte[] keyBytes = HexToBytes(key);

                // 执行解密
                var aes = new AES(keySize);
                byte[] plaintext = aes.Decrypt(input, keyBytes);

                // 显示结果
                txtResult.Text = BytesToHex(plaintext);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"错误: {ex.Message}", "解密错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private int GetSelectedKeySize()
        {
            switch (cmbAlgorithm.SelectedIndex)
            {
                case 0:
                    return 128;
                case 1:
                    return 192;
                case 2:
                    return 256;
                default:
                    throw new InvalidOperationException("无效的算法选择");
            }
        }
        private string SanitizeHex(string input)
        {
            return Regex.Replace(input.ToUpper(), "[^0-9A-F]", "");
        }

        private void ValidateInput(string plaintext, string key, int keySize)
        {
            // 验证明文长度（固定128位）
            if (plaintext.Length != 32)
                throw new ArgumentException("输入必须为128位十六进制字符（16字节）");

            // 验证密钥长度
            int requiredKeyLength = keySize / 4; // 128/4=32, 192/4=48, 256/4=64
            if (key.Length != requiredKeyLength)
                throw new ArgumentException($"密钥必须为{requiredKeyLength}位十六进制字符（{keySize}位）");
        }
        private static byte[] HexToBytes(string hex)
        {
            if (hex.Length % 2 != 0)
                throw new ArgumentException("十六进制字符串长度必须为偶数");

            byte[] bytes = new byte[hex.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
                bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
            return bytes;
        }
        private static string BytesToHex(byte[] bytes)
        {
            return BitConverter.ToString(bytes).Replace("-", " ");
        }

    }
}
